/**
 * 
 */
package oop.ex2;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import oop.ex2.SearchEngine.SearchEngine;
import oop.ex2.filters.exceptions.FilterException;
import oop.ex2.parser.exceptions.ParsingException;
import oop.ex2.util.*;
import oop.ex2.util.exceptions.*;

/**
 * Implementation of search engine, finds files correspond to 
 * given set of filters.
 */
public class MyFileSearch {

	/**
	 * Search engine operation.
	 * @param args args[0] = Source folders to look in.
	 * 			   args[1] = File containing all desired filters.
	 */
	public static void main(String[] args) {
		if ( !checkValidity(args) ) {
		    System.err.println("Error:Invalid command line parameters");
		    System.exit(1);
		}
		SearchEngine searcher = new SearchEngine(args[0]);
		try{	
			FilterReader reader = new FilterReader(args[1]);
			String currentFilter;
			FileIterator iterator = reader.iterator();
			while(iterator.hasNext()){
				currentFilter = iterator.next();
				System.out.println(currentFilter);				
				printFiles(searcher.search(currentFilter));
			}			
		}
		catch( ReaderIOException e){
			System.err.println(e.getMessage());
		}
		catch( FilterException e){
		    System.err.println(e.getMessage());
			}
		catch( ParsingException e){
			System.err.println(e.getMessage());
		}
		catch( IOException e){
			System.out.println("Error:I/O failure");
		}

	}
	/**
	 * Prints the name of all the filters in list.
	 * @param files List of files to be printed.
	 */
	private static void printFiles(ArrayList<File> files){
	    try{
    		for(File currentFile : files){
    			System.out.println(currentFile.getCanonicalPath());
    		}
	    }
	    catch( IOException e) {
	        System.err.println("Error:I/O failure");
	        System.exit(1);
	    }
	}
	/**
	 * Checks if user's input is valid.
	 * @param args User's input.
	 * @return True if data is valid, else otherwise.
	 */
	private static boolean checkValidity ( String[] args ) {
	    if ( args == null || args.length != 2 ) {
	        return false;
	    }
	    File source  = new File(args[0]);
	    File filter = new File(args[1]);
	    return ( filter.exists() && filter.isFile() && source.exists() );
	}
}
